import java.util.HashMap;
import java.util.ArrayList;

public class PComp {    
    public void compile(ArrayList<PArgs> argLists) {
    }
    
    private static HashMap<Integer, ArrayList<PArgs>>  
    partitionByArgCount(ArrayList<PArgs> alts) {
        HashMap<Integer, ArrayList<PArgs>> ret =
            new HashMap<Integer, ArrayList<PArgs>>();    
        for (PArgs args : alts) {
            Integer n = args.count();
            ArrayList<PArgs> lst = ret.get(n);      
            if (null == lst) {
                lst = new ArrayList<PArgs>();
                lst.add(args);
                ret.put(n, lst);
            } else {
                lst.add(args);
            }  
        }
        return ret;
    }
    
    private static void printPartitions(
        HashMap<Integer, ArrayList<PArgs>> alts) {
        for (Integer i : alts.keySet()) {
            System.out.println("--- Size:" + i);
            for (PArgs args : alts.get(i)) {
                System.out.println(args);
            }
        }        
    }

    private static PArgs replaceBackrefs(PArgs args) {
        for (int i = 0; i < args.count(); ++i) {
            if (args.get(i) instanceof PVar) {
                String vi = ((PVar) args.get(i)).name();
                for (int j = i + 1; j < args.count(); ++j) {
                    if (args.get(j) instanceof PVar) {
                        String vj = ((PVar) args.get(i)).name();
                        if (vi.equals(vj)) {
                            args.set(j, new PVarRef((PVar) args.get(i)));
                        }
                    }
                }
            }
        }
        return args;
    }
    
    public static void main(String[] cmdLineArgs) {
        ArrayList<PArgs> alts = new ArrayList<PArgs>();
        HashMap<Integer, ArrayList<PArgs>> p;
        PArgs a0, a1, a2, a3;
        Object[] a_0 = {
            new PVar("x", new Integer(666)),
            new Integer(3),
            new OddQuery("n")
        };
        Object[] a_1 = {
            new PVar("x", null),
            new OddQuery("z"),
            new PVar("x", null)
        };
        Object[] a_2 = {
            new PVar("x", null),
            new Integer(3)
        };                    
        alts.add(a0 = new PArgs(a_0));
        alts.add(a1 = new PArgs(a_1));
        alts.add(a2 = new PArgs(a_2));
        replaceBackrefs(a0);
        replaceBackrefs(a1);
        replaceBackrefs(a2);
        p = PComp.partitionByArgCount(alts);
        printPartitions(p);
  }
}    
         



